package com.sjft.cloud.commons.security.rest;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpStatus;
import com.sjft.cloud.commons.core.func.Fn;
import com.sjft.cloud.commons.core.resp.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * RestAuthExceptionEntryPoint
 *
 * @author Jin
 */
@Slf4j
@SuppressWarnings("all")
public class RestAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";

    private ObjectMapper objectMapper;

    public RestAuthExceptionEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter printWriter = response.getWriter();
        if (Fn.startWith(authException.getMessage(), "Invalid")) {
            printWriter.append(objectMapper.writeValueAsString(R
                    .error()
                    .setCode(5000)
                    .setMessage("accessToken 已过期请重新登录！")));

        } else {
            printWriter.append(objectMapper.writeValueAsString(R
                    .error()
                    .setMessage(authException instanceof InsufficientAuthenticationException ? "请求未授权！" : authException.getMessage())));

        }
        printWriter.close();


    }
}
